<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="上面我们虽然完成了用中断控制电机转动的程序，但实际上这个程序还是没多少实用价值的，我们不能每次想让它转动的时候都上下电啊，是吧。还有就是它不但能正转还得能反转啊，也就是说不但能转过去，还得能转回来呀。好吧，我们就来做一个实例程序吧，结合第 8 章的按键程序，我们设计这样一个功能程序：按数字键 1～9，控制电机转过 1～9 圈；配合上下键改变转动方向，按向上键后正向转 1～9 圈，向下键则反向转 1">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="9.8、电机控制程序基础">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu063/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="上面我们虽然完成了用中断控制电机转动的程序，但实际上这个程序还是没多少实用价值的，我们不能每次想让它转动的时候都上下电啊，是吧。还有就是它不但能正转还得能反转啊，也就是说不但能转过去，还得能转回来呀。好吧，我们就来做一个实例程序吧，结合第 8 章的按键程序，我们设计这样一个功能程序：按数字键 1～9，控制电机转过 1～9 圈；配合上下键改变转动方向，按向上键后正向转 1～9 圈，向下键则反向转 1">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-27T04:55:17.366Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="9.8、电机控制程序基础">
<meta name="twitter:description" content="上面我们虽然完成了用中断控制电机转动的程序，但实际上这个程序还是没多少实用价值的，我们不能每次想让它转动的时候都上下电啊，是吧。还有就是它不但能正转还得能反转啊，也就是说不但能转过去，还得能转回来呀。好吧，我们就来做一个实例程序吧，结合第 8 章的按键程序，我们设计这样一个功能程序：按数字键 1～9，控制电机转过 1～9 圈；配合上下键改变转动方向，按向上键后正向转 1～9 圈，向下键则反向转 1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu063/">





  <title>9.8、电机控制程序基础 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu063/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">9.8、电机控制程序基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:36:46+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>上面我们虽然完成了用中断控制电机转动的程序，但实际上这个程序还是没多少实用价值的，我们不能每次想让它转动的时候都上下电啊，是吧。还有就是它不但能正转还得能反转啊，也就是说不但能转过去，还得能转回来呀。好吧，我们就来做一个实例程序吧，结合第 8 章的按键程序，我们设计这样一个功能程序：按数字键 1～9，控制电机转过 1～9 圈；配合上下键改变转动方向，按向上键后正向转 1～9 圈，向下键则反向转 1～9 圈；左键固定正转 90 度，右键固定反转 90；Esc 键终止转动。通过这个程序，我们也可以进一步体会到如何用按键来控制程序完成复杂的功能，以及控制和执行模块之间如何协调工作，而你的编程水平也可以在这样的实践练习中得到锻炼和提升。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit KEY_IN_1 = P2^4;</span><br><span class="line">sbit KEY_IN_2 = P2^5;</span><br><span class="line">sbit KEY_IN_3 = P2^6;</span><br><span class="line">sbit KEY_IN_4 = P2^7;</span><br><span class="line">sbit KEY_OUT_1 = P2^3;</span><br><span class="line">sbit KEY_OUT_2 = P2^2;</span><br><span class="line">sbit KEY_OUT_3 = P2^1;</span><br><span class="line">sbit KEY_OUT_4 = P2^0;</span><br><span class="line">unsigned char code KeyCodeMap[4][4] = &#123; //矩阵按键编号到标准键盘键码的映射表</span><br><span class="line">    &#123; 0x31, 0x32, 0x33, 0x26 &#125;, //数字键 1、数字键 2、数字键 3、向上键</span><br><span class="line">    &#123; 0x34, 0x35, 0x36, 0x25 &#125;, //数字键 4、数字键 5、数字键 6、向左键</span><br><span class="line">    &#123; 0x37, 0x38, 0x39, 0x28 &#125;, //数字键 7、数字键 8、数字键 9、向下键</span><br><span class="line">    &#123; 0x30, 0x1B, 0x0D, 0x27 &#125; //数字键 0、ESC 键、 回车键、 向右键</span><br><span class="line">&#125;;</span><br><span class="line">unsigned char KeySta[4][4] = &#123; //全部矩阵按键的当前状态</span><br><span class="line">    &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;</span><br><span class="line">&#125;;</span><br><span class="line">signed long beats = 0; //电机转动节拍总数</span><br><span class="line">void KeyDriver();</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1; //使能总中断</span><br><span class="line">    TMOD = 0x01; //设置 T0 为模式 1</span><br><span class="line">    TH0 = 0xFC; //为 T0 赋初值 0xFC67，定时 1ms</span><br><span class="line">    TL0 = 0x67;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">   </span><br><span class="line">    while (1)&#123;</span><br><span class="line">        KeyDriver(); //调用按键驱动函数</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 步进电机启动函数，angle-需转过的角度 */</span><br><span class="line">void StartMotor(signed long angle)&#123;</span><br><span class="line">    //在计算前关闭中断，完成后再打开，以避免中断打断计算过程而造成错误</span><br><span class="line">    EA = 0;</span><br><span class="line">    beats = (angle * 4076) / 360; //实测为 4076 拍转动一圈</span><br><span class="line">    EA = 1;</span><br><span class="line">&#125;</span><br><span class="line">/* 步进电机停止函数 */</span><br><span class="line">void StopMotor()&#123;</span><br><span class="line">    EA = 0;</span><br><span class="line">    beats = 0;</span><br><span class="line">    EA = 1;</span><br><span class="line">&#125;</span><br><span class="line">/* 按键动作函数，根据键码执行相应的操作，keycode-按键键码 */</span><br><span class="line">void KeyAction(unsigned char keycode)&#123;</span><br><span class="line">    static bit dirMotor = 0; //电机转动方向</span><br><span class="line">    //控制电机转动 1-9 圈</span><br><span class="line">    if ((keycode&gt;=0x30) &amp;&amp; (keycode&lt;=0x39))&#123;</span><br><span class="line">        if (dirMotor == 0)&#123;</span><br><span class="line">            StartMotor(360*(keycode-0x30));</span><br><span class="line">        &#125;else&#123;</span><br><span class="line">            StartMotor(-360*(keycode-0x30));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;else if (keycode == 0x26)&#123; //向上键，控制转动方向为正转</span><br><span class="line">        dirMotor = 0;</span><br><span class="line">    &#125;else if (keycode == 0x28)&#123; //向下键，控制转动方向为反转</span><br><span class="line">        dirMotor = 1;</span><br><span class="line">    &#125;else if (keycode == 0x25)&#123; //向左键，固定正转 90 度</span><br><span class="line">        StartMotor(90);</span><br><span class="line">    &#125;else if (keycode == 0x27)&#123; //向右键，固定反转 90 度</span><br><span class="line">        StartMotor(-90);</span><br><span class="line">    &#125;else if (keycode == 0x1B)&#123; //Esc 键，停止转动</span><br><span class="line">        StopMotor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 按键驱动函数，检测按键动作，调度相应动作函数，需在主循环中调用 */</span><br><span class="line">void KeyDriver()&#123;</span><br><span class="line">    unsigned char i, j;</span><br><span class="line">    static unsigned char backup[4][4] = &#123; //按键值备份，保存前一次的值</span><br><span class="line">        &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;, &#123;1, 1, 1, 1&#125;</span><br><span class="line">    &#125;;</span><br><span class="line">   </span><br><span class="line">    for (i=0; i&lt;4; i++)&#123; //循环检测 4*4 的矩阵按键</span><br><span class="line">        for (j=0; j&lt;4; j++)&#123;</span><br><span class="line">            if (backup[i][j] != KeySta[i][j])&#123; //检测按键动作</span><br><span class="line">                if (backup[i][j] != 0)&#123; //按键按下时执行动作</span><br><span class="line">                    KeyAction(KeyCodeMap[i][j]); //调用按键动作函数</span><br><span class="line">                &#125;</span><br><span class="line">                backup[i][j] = KeySta[i][j]; //刷新前一次的备份值</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 按键扫描函数，需在定时中断中调用，推荐调用间隔 1ms */</span><br><span class="line">void KeyScan()&#123;</span><br><span class="line">    unsigned char i;</span><br><span class="line">    static unsigned char keyout = 0; //矩阵按键扫描输出索引</span><br><span class="line">   </span><br><span class="line">    static unsigned char keybuf[4][4] = &#123; //矩阵按键扫描缓冲区</span><br><span class="line">        &#123;0xFF, 0xFF, 0xFF, 0xFF&#125;, &#123;0xFF, 0xFF, 0xFF, 0xFF&#125;,</span><br><span class="line">        &#123;0xFF, 0xFF, 0xFF, 0xFF&#125;, &#123;0xFF, 0xFF, 0xFF, 0xFF&#125;</span><br><span class="line">    &#125;;</span><br><span class="line">   </span><br><span class="line">    //将一行的 4 个按键值移入缓冲区</span><br><span class="line">    keybuf[keyout][0] = (keybuf[keyout][0] &lt;&lt; 1) | KEY_IN_1;</span><br><span class="line">    keybuf[keyout][1] = (keybuf[keyout][1] &lt;&lt; 1) | KEY_IN_2;</span><br><span class="line">    keybuf[keyout][2] = (keybuf[keyout][2] &lt;&lt; 1) | KEY_IN_3;</span><br><span class="line">    keybuf[keyout][3] = (keybuf[keyout][3] &lt;&lt; 1) | KEY_IN_4;</span><br><span class="line">    //消抖后更新按键状态</span><br><span class="line">    for (i=0; i&lt;4; i++)&#123; //每行 4 个按键，所以循环 4 次</span><br><span class="line">        if ((keybuf[keyout][i] &amp; 0x0F) == 0x00)&#123;</span><br><span class="line">            //连续 4 次扫描值为 0，即 4*4ms 内都是按下状态时，可认为按键已稳定的按下</span><br><span class="line">            KeySta[keyout][i] = 0;</span><br><span class="line">        &#125;else if ((keybuf[keyout][i] &amp; 0x0F) == 0x0F)&#123;</span><br><span class="line">            //连续 4 次扫描值为 1，即 4*4ms 内都是弹起状态时，可认为按键已稳定的弹起</span><br><span class="line">            KeySta[keyout][i] = 1;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    //执行下一次的扫描输出</span><br><span class="line">    keyout++; //输出索引递增</span><br><span class="line">    keyout = keyout &amp; 0x03; //索引值加到 4 即归零</span><br><span class="line">    //根据索引，释放当前输出引脚，拉低下次的输出引脚</span><br><span class="line">    switch (keyout)&#123;</span><br><span class="line">        case 0: KEY_OUT_4 = 1; KEY_OUT_1 = 0; break;</span><br><span class="line">        case 1: KEY_OUT_1 = 1; KEY_OUT_2 = 0; break;</span><br><span class="line">        case 2: KEY_OUT_2 = 1; KEY_OUT_3 = 0; break;</span><br><span class="line">        case 3: KEY_OUT_3 = 1; KEY_OUT_4 = 0; break;</span><br><span class="line">        default: break;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 电机转动控制函数 */</span><br><span class="line">void TurnMotor()&#123;</span><br><span class="line">    unsigned char tmp; //临时变量</span><br><span class="line">    static unsigned char index = 0; //节拍输出索引</span><br><span class="line">    unsigned char code BeatCode[8] = &#123; //步进电机节拍对应的 IO 控制代码</span><br><span class="line">        0xE, 0xC, 0xD, 0x9, 0xB, 0x3, 0x7, 0x6</span><br><span class="line">    &#125;;</span><br><span class="line">   </span><br><span class="line">    if (beats != 0)&#123; //节拍数不为 0 则产生一个驱动节拍</span><br><span class="line">        if (beats &gt; 0)&#123; //节拍数大于 0 时正转</span><br><span class="line">            index++; //正转时节拍输出索引递增</span><br><span class="line">            index = index &amp; 0x07; //用&amp;操作实现到 8 归零</span><br><span class="line">            beats--; //正转时节拍计数递减</span><br><span class="line">            &#125;else&#123; //节拍数小于 0 时反转</span><br><span class="line">            index--; //反转时节拍输出索引递减</span><br><span class="line">            index = index &amp; 0x07; //用&amp;操作同样可以实现到-1 时归 7</span><br><span class="line">            beats++; //反转时节拍计数递增</span><br><span class="line">        &#125;</span><br><span class="line">        tmp = P1; //用 tmp 把 P1 口当前值暂存</span><br><span class="line">        tmp = tmp &amp; 0xF0; //用&amp;操作清零低 4 位</span><br><span class="line">        tmp = tmp | BeatCode[index]; //用|操作把节拍代码写到低 4 位</span><br><span class="line">        P1 = tmp; //把低 4 位的节拍代码和高 4 位的原值送回 P1</span><br><span class="line">    &#125;else&#123; //节拍数为 0 则关闭电机所有的相</span><br><span class="line">        P1 = P1 | 0x0F;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，用于按键扫描与电机转动控制 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    static bit div = 0;</span><br><span class="line">    TH0 = 0xFC; //重新加载初值</span><br><span class="line">    TL0 = 0x67;</span><br><span class="line">    KeyScan(); //执行按键扫描</span><br><span class="line">    //用一个静态 bit 变量实现二分频，即 2ms 定时，用于控制电机</span><br><span class="line">    div = ~div;</span><br><span class="line">    if (div == 1)&#123;</span><br><span class="line">        TurnMotor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个程序是第 8 章和本章知识的一个综合——用按键控制步进电机转动。程序中有这么几点值得注意，我们分述如下：</p>
<ul>
<li>针对电机要完成正转和反转两个不同的操作，我们并没有使用正转启动函数和反转启动函数这么两个函数来完成，也没有在启动函数定义的时候增加一个形式参数来指明其方向。我们这里的启动函数 void StartMotor(signed long angle)与单向正转时的启动函数唯一的区别就是把形式参数 angle 的类型从 unsigned long 改为了 signed long，我们用有符号数固有的正负特性来区分正转与反转，正数表示正转 angle 度，负数就表示反转 angle 度，这样处理是不是很简洁又很明了呢？而你对有符号数和无符号数的区别用法是不是也更有体会了？</li>
<li>针对终止电机转动的操作，我们定义了一个单独的 StopMotor 函数来完成，尽管这个函数非常简单，尽管它也只在 Esc 按键分支内被调用了，但我们仍然把它单独提出来作为了一个函数。而这种做法就是基于这样一条编程原则：尽可能用单独的函数来完成硬件的某种操作，当一个硬件包含多个操作时，把这些操作函数组织在一起，形成一个对上层的统一接口。这样的层次化处理，会使得整个程序条理清晰，既有利于程序的调试维护，又有利于功能的扩充。</li>
<li>中断函数中要处理按键扫描和电机驱动两件事情，而为了避免中断函数过于复杂，我们就又分出了按键扫描和电机驱动两个函数（这也同样符合上述 2 的编程原则），而中断函数的逻辑就变得简洁而清晰了。这里还有个矛盾，就是按键扫描我们选择的定时时间是 1ms，而本章之前的实例中电机节拍持续时间都是 2ms；很显然，用 1ms 的定时可以定出 2ms 的间隔，而用 2ms 的定时却得不到准确的 1ms 间隔；所以我们的做法就是，定时器依然定时 1ms，然后用一个 bit 变量做标志，每 1ms 改变一次它的值，而我们只选择值为 1 的时候执行一次动作，这样就是 2ms 的间隔了；如果我要 3ms、4ms„„呢，把 bit 改为 char 或 int 型，然后对它们递增，判断到哪个值该归零，就可以了。这就是在硬件定时器的基础上实现准确的软件定时，其实类似的操作我们在讲数码管的时候也用过了，回想一下吧。</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu062/" rel="next" title="9.7、电机控制程序基础">
                <i class="fa fa-chevron-left"></i> 9.7、电机控制程序基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu064/" rel="prev" title="9.9、电机控制程序基础">
                9.9、电机控制程序基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
